<?php
namespace app\api\controller;
use app\common\controller\CommonApi;

class User extends CommonApi{

    /**
     * [getUserInfo 当前用户信息]
     * @return [type] [description]
     */
    public function getUserInfo(){
        //今日访客
        $this->user_info['today_visit'] = db('visiter')->whereTime('add_time','d')->where('user_id',UID)->count();
        $this->apiReturn(1,'用户资料',$this->user_info);
    }

    //我的需求、日记、服务、
    public function myIssue(){
        $validate = new \think\validate(['type' => 'require|in:1,2,3'],['type.require' => '请选择类型','type.in' => '类型有误']);
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        //需求
        if(intval($this->post['type']) == 1){
            $list = model('common/need')->dataCheck(model('common/need')->needList(['n.user_id' => UID],'n.add_time desc',$this->p));   
        }

        //日记
        if(intval($this->post['type']) == 2){
            $list = model('common/nearby')->dataCheck(model('common/nearby')->nearbyList(['n.user_id' => UID],'n.add_time desc',$this->p));
        }
        //服务
        if(intval($this->post['type']) == 3){
            $list = model('common/service')->dataCheck(model('common/service')->serviceList(['s.user_id' => UID],'s.add_time desc',$this->p));
        }
        $this->apiReturn(1,'列表',$list);
    }


    /**
     * [changInfo 修改信息]
     * @return [type] [description]
     */
    public function changInfo(){
        $validate = validate('common/user');
        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $model = model('common/user');

        $this->post = $model->delData($this->post,['balance','f_balance','token','password','id','im_password','im_account']);
        //主要用户修改im信息用
        $this->post['im_account'] = $this->user_info['im_account'];
        $result = $model->allowField(true)->save($this->post,['id' => UID]);

        if($result === false){
            $this->apiReturn(0, '资料修改失败，请稍后再试');
        }

        $this->apiReturn(1,'资料修改成功',model('common/user')->getUserInfo(['id'=>UID]));
    }

    //修改手机号
    public function changeMobile(){
        $validate = new \think\validate([
            'account' => 'require|regex:/^1[345789]{1}\d{9}$/',
            'code' => 'require'
        ],[
            'account.require' => '请输入手机号',
            'account.regex' => '手机号格式错误',
            'code.require' => '请输入验证码'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        $res = model('common/send_code')->checkCode(trim($this->post['account']),trim($this->post['code']),2);
        if($res['status'] == 0){
            $this->apiReturn(0,$res['msg']);
        }

        if(db('user')->where('account',trim($this->post['account']))->find()){
            $this->apiReturn(0,'该手机号已经存在');
        }

        if(!model('common/user')->save(['account' => trim($this->post['account'])],['id' => UID])){
            $this->apiReturn(0,'修改手机号失败');
        }
        $this->apiReturn(1,'修改成功',model('common/user')->getUserInfo(['id' => UID]));
    }



    //修改登录密码
    public function changePwd(){

    }

    //更换背景封面
    public function changeBg(){
        if(!isset($this->post['bg']) || trim($this->post['bg']) == ''){
            $this->apiReturn(0,'请上传背景封面');
        }

        if(!db('user')->where('id',UID)->update(['bg' => trim($this->post['bg']),'bg_change_time' => time()])){
            $this->apiReturn(0,'更换背景封面失败');
        }
        $this->apiReturn(1,'更换成功');
    }

    //添加收藏
    public function addCollect(){
        $validate = new \think\validate([
            'type' => 'require|in:1,2,3',
            'id' => 'require'
        ],[
            'type.require' => '参数type丢失',
            'type.in' => '参数type错误',
            'id.require' => '参数id丢失'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        switch($this->post['type']){
            case 1 : $model = db('need'); break;
            case 2 : $model = db('nearby') ; break;
            case 3 : $model = db('service') ; break;
        }
        $res = $model->where('status',1)->where('id',intval($this->post['id']))->find();
        if(is_null($res)){
            $this->apiReturn(0,'发布信息不存在或已被删除');
        }  

        if($res['user_id'] == UID){
            $this->apiReturn(0,'不能收藏自己的发布信息');
        }
        if($coll = db('collect')->where('type',$this->post['type'])->where('foreign_key',intval($this->post['id']))->where('user_id',UID)->find()){
            $this->apiReturn(1,'收藏成功',$coll['id']);
        }
        $insert = db('collect')->insertGetId([
                'user_id' => UID,
                'foreign_key' => intval($this->post['id']),
                'type' => $this->post['type'],
                'add_time' => time()
        ]);
        if(!$insert){
            $this->apiReturn(0,'收藏失败');
        }

        $this->apiReturn(1,'收藏成功',$insert);
    }


    //取消收藏
    public function offCollect(){
        $validate = new \think\validate([
            'type' => 'require|in:1,2,3',
            'id' => 'require'
        ],[
            'type.require' => '参数type丢失',
            'type.in' => '参数type错误',
            'id.require' => '参数id丢失'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if(!db('collect')->where('type',$this->post['type'])->where('user_id',UID)->where('foreign_key',intval($this->post['id']))->find()){
            $this->apiReturn(0,'取消成功');
        }

        if(!db('collect')->where('type',$this->post['type'])->where('user_id',UID)->where('foreign_key',intval($this->post['id']))->delete()){
            $this->apiReturn(0,'取消失败，请稍后再试');
        }

        $this->apiReturn(1,'取消成功');
    }

    /**
     * [collectList 收藏列表]
     * @return [type] [收藏类型 1：需求 2：附近圈 3：服务]
     */
    public function collectList(){
        if(!isset($this->post['type']) || !in_array($this->post['type'],[1,2,3])){
            $this->apiReturn(0,'参数type错误');
        }
        $where['c.type'] = $this->post['type'];
        $where['c.user_id'] = UID;
        $list = model('common/collect')->getList($where,$this->post['type'],$this->p);

        $this->apiReturn(1,'',$list);
    }

    //申请提现
    public function withdraw(){
        $validate = new \think\validate([
            'bank' => 'require',
            'name' => 'require',
            'card_no' => 'require',
            'price' => 'require'
        ],[
            'bank.require' => '请输入开户行名称',
            'name.require' => '请输入开户人姓名',
            'card_no.require' => '请输入银行卡号',
            'price.require' => '请输入提现金额'
        ]);

        if($validate->check($this->post) === false){
            $this->apiReturn(0,$validate->getError());
        }

        if($this->user_info['balance'] < floatval($this->post['price'])){
            $this->apiReturn(0,'余额不足');
        }

        //最低提现金额
        $min_withdraw_price = db('web_config')->where('key','withdraw_price')->value('value');
        if(floatval($this->post['price']) < $min_withdraw_price){
            $this->apiReturn(0,'提现金额最低为'.$min_withdraw_price);
        }

        db()->startTrans();

        if(!db('withdraw')->insert([
            'user_id' => UID,
            'bank' => trim($this->post['bank']),
            'name' => trim($this->post['name']),
            'card_no' => trim($this->post['card_no']),
            'price' => floatval($this->post['price']),
            'add_time' => time()
        ])){
            db()->rollback();
            $this->apiReturn(0,'申请失败，请稍后再试');
        }

        if(!db('user')->where('id',UID)->update([
            'balance' => ['dec',floatval($this->post['price'])],
            'f_balance' => ['inc',floatval($this->post['price'])]
        ])){
            db()->rollback();
            $this->apiReturn(0,'信息更新失败，请稍后再试');
        }

        db()->commit();
        $this->apiReturn(1,'申请提现成功，请耐心等待审核消息');
    }


    //提现列表
    public function withdrawList(){
        $list = db('withdraw')
            ->where('user_id',UID)
            ->order('add_time desc')
            ->field('bank,name,card_no,price,FROM_UNIXTIME(add_time,"%Y-%m-%d %H:%i") as add_time,status')
            ->limit(($this->p-1)*config('page_size'),config('page_size'))
            ->select();
        $this->apiReturn(1,'提现列表',$list);
    }


    //余额明细
    public function  bill(){
        $list = db('bill')
            ->where('user_id',UID)
            ->order('add_time desc')
            ->limit(($this->p-1)*config('page_size'),config('page_size'))
            ->field('id,num,type,foreign_key,FROM_UNIXTIME(add_time,"%Y-%m-%d %H:%i") as add_time')
            ->select();

        foreach($list as $key => $val){
            switch($val['type']){
                case 1 : 
                    $list[$key]['content'] = '发红包';
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 2 :
                    $list[$key]['content'] = '领取红包';
                    $list[$key]['num'] = '+'.$val['num'];
                    break;
                case 3 :
                    $need = db('need_apply')->alias('a')->join(['bz_need' => 'n'],'n.id = a.foreign_key','left')->where('a.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '需求定金支付-'.$need['title'];
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 4 :
                    $need = db('need_apply')->alias('a')->join(['bz_need' => 'n'],'n.id = a.foreign_key','left')->where('a.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '需求接单-'.$need['title'];
                    $list[$key]['num'] = '+'.$val['num'];
                    break;
                case 5 :
                    $ad = db('ad_buy')->alias('b')->join(['bz_ad_position' => 'p'],'p.id = b.position_id','left')->where('b.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '购买-'.$ad['position'].$ad['buy_num'].'次';
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 6 :
                    $service = db('service_buy')->alias('b')->join(['bz_service' => 's'],'s.id = b.foreign_key','left')->where('b.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '服务定金支付-'.$service['title'];
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 7 :
                    $list[$key]['content'] = '红包退款';
                    $list[$key]['num'] = '+'.$val['num'];
                    break;
                case 8 :
                    $service = db('service_buy')->alias('b')->join(['bz_service' => 's'],'s.id = b.foreign_key','left')->where('b.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '服务定金-'.$service['title'];
                    $list[$key]['num'] = '+'.$val['num'];
                    break;
                case 9 :
                    $service = db('service_buy')->alias('b')->join(['bz_service' => 's'],'s.id = b.foreign_key','left')->where('b.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '服务打赏-'.$service['title'];
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 10 :
                    $service = db('service_buy')->alias('b')->join(['bz_service' => 's'],'s.id = b.foreign_key','left')->where('b.id',$val['foreign_key'])->find();
                    $list[$key]['content'] = '服务打赏-'.$service['title'];
                    $list[$key]['num'] = '+'.$val['num'];
                    break;

                case 11 : 
                    $list[$key]['content'] = '购买会员';
                    $list[$key]['num'] = '-'.$val['num'];
                    break;
                case 12 :
                    $list[$key]['content'] = '余额提现';
                    $list[$key]['num'] = '-'.$val['num'];
                    break;   
                case 13 :
                    $list[$key]['content'] = '购买位置';
                    $list[$key]['num'] = '-'.$val['num'];
                    break;   
            }
        }

        $this->apiReturn(1,'账单',$list);
    }
}
